package com.googlecode.jwsm;

import java.io.*;
import java.util.logging.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcommon.j2ee.*;

import com.googlecode.jwsm.security.User;

/**
 * Servlet implementation class for Servlet: XSLTServlet
 *
 * @web.servlet
 *   name="XSLTServlet"
 *   display-name="XSLTServlet"
 *
 * @web.servlet-mapping
 *   url-pattern="/XSLTServlet"
 *
 */
public class XSLTServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			User user = JWSMSecurity.getUser(request, response, true);
			if ((!request.getParameter("action").equals("download")) && (!user.hasPrivilege("jwsm.xslt_manage"))) {
				response.sendRedirect("index.jsp?error=Insufficient privileges");
			}
		} catch(Exception exc) {
			throw new SecurityException(exc.getMessage());
		}

		String xsltName = request.getParameter("xslt");
		int type = Integer.parseInt(request.getParameter("type"));
		XSLT xslt;
		if (type == XSLT.INCOMING) {
			xslt = ServiceManager.getInstance().getIncomingXSLT(xsltName);
		} else {
			xslt = ServiceManager.getInstance().getOutgoingXSLT(xsltName);
		}
		if (request.getParameter("action").equals("delete")) {
			if (XSLT.delete(xslt)) {
				response.sendRedirect("index.jsp?message=XSLT " + xslt.getName() + " was successfully deleted.");
			} else {
				response.sendRedirect("index.jsp?error=XSLT " + xslt.getName() + " was not able to be deleted.");
			}
		} else if (request.getParameter("action").equals("download")) {
			response.setContentType("text/xml");
			response.addHeader("Content-Disposition", "Attachment; filename=\"" + xslt.getFilename() + "\"");
			OutputStream out = response.getOutputStream();
			FileInputStream fis = new FileInputStream(new File(new File(Uploader.directory, ".xslts"), xslt.getFilename()));
			byte[] b = new byte[512];
			int len;
			while ((len = fis.read(b)) != -1) {
				out.write(b, 0, len);
			}
			out.flush();
			out.close();
			fis.close();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Thread.currentThread().setName("XSLT Servlet");
		MultipartReader reader = new MultipartReader(request.getInputStream());
		PartInputStream part;
		String name = null;
		String defaultClass = null;
		String filename = null;
		String type = null;
		File directory = new File(Uploader.directory, ".xslts");
		while ((part = reader.nextPart()) != null) {
			if ((part.isFile()) && (part.getFilename().trim().length() > 0)) {
				filename = part.getFilenameShort();
				directory.mkdirs();
				File file = new File(directory, filename);
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buf = new byte[512];
				int len;
				while((len = part.read(buf)) != -1) {
					fos.write(buf, 0, len);
				}
				fos.flush();
				fos.close();
			} else if (part.getName().equals("name")) {
				name = part.getValue();
			} else if (part.getName().equals("defaultClass")) {
				defaultClass = part.getValue();
			} else if (part.getName().equals("type")) {
				type = part.getValue();
			}
			part.close();
		}
		if ((name != null) && (filename != null)) {
			XSLT xslt = new XSLT();
			xslt.setName(name);
			xslt.setFilename(filename);
			xslt.setDefaultAssociation(defaultClass);
			if (type.equals("incoming")) {
				xslt.setType(XSLT.INCOMING);
			} else {
				xslt.setType(XSLT.OUTGOING);
			}
			try {
				String extension;
				if (xslt.isIncoming()) {
					extension = ".incoming.config";
				} else {
					extension = ".outgoing.config";
				}
				XSLT.save(xslt, new File(directory, xslt.getName() + extension));
				if (xslt.isIncoming()) {
					ServiceManager.getInstance().registerIncomingXSLT(xslt);
				} else {
					ServiceManager.getInstance().registerOutgoingXSLT(xslt);
				}
			} catch(Exception exc) {
				exc.printStackTrace();
				Log.get().throwing(XSLTServlet.class.getName(), "doPost", exc);
				response.sendRedirect("index.jsp?error=Unable to XSLT configuration information");
				return;
			}
			response.sendRedirect("index.jsp?message=The XSLT " + xslt.getName() + " was successfully registered.");
		} else {
			response.sendRedirect("index.jsp?error=Improper data sent for XSLT, registration failed.");
		}
	}
}